import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  TextField,
  Button,
  Tabs,
  Tab,
  Switch,
  FormControlLabel,
  Select,
  MenuItem,
  FormControl,
  Paper,
  IconButton,
  Snackbar,
  Alert,
  AlertTitle,
  Chip,
} from '@mui/material';
import {
  Save as SaveIcon,
  Refresh as RefreshIcon,
  Visibility as VisibilityIcon,
  VisibilityOff as VisibilityOffIcon,
  CheckCircle as CheckCircleIcon,
  Warning as WarningIcon,
  Error as ErrorIcon,
  Info as InfoIcon,
} from '@mui/icons-material';
import { settings } from '../../utils/core/settings.ts';
import { getModelName } from './AIModelList.tsx';
import { SelectChangeEvent } from '@mui/material/Select';

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}

function TabPanel(props: TabPanelProps) {
  const { children, value, index, ...other } = props;

  return (
    <Box
      role="tabpanel"
      hidden={value !== index}
      id={`settings-tabpanel-${index}`}
      aria-labelledby={`settings-tab-${index}`}
      sx={{ p: 3 }}
      {...other}
    >
      {value === index && <Box>{children}</Box>}
    </Box>
  );
}

const SettingsPanel: React.FC = () => {
  const [tabValue, setTabValue] = useState(0);
  const [loading, setLoading] = useState(true);
  const [showApiKey, setShowApiKey] = useState(false);
  const [snackbar, setSnackbar] = useState<{
    open: boolean;
    message: string;
    severity: 'success' | 'error' | 'info';
  }>({
    open: false,
    message: '',
    severity: 'info',
  });

  // 设置字段
  const [deepseekApiKey, setDeepseekApiKey] = useState('');
  const [siliconflowApiKey, setSiliconflowApiKey] = useState('');
  const [aiModel, setAiModel] = useState('deepseek-chat');
  const [theme, setTheme] = useState<'light' | 'dark' | 'system'>('system');
  const [autoSave, setAutoSave] = useState(true);
  const [autoSaveInterval, setAutoSaveInterval] = useState(60);
  const [fontSize, setFontSize] = useState(16);
  const [fontFamily, setFontFamily] = useState('Arial');
  const [lineHeight, setLineHeight] = useState(1.5);
  const [selectedModel, setSelectedModel] = useState('deepseek-chat');
  const [selectedProvider, setSelectedProvider] = useState<'deepseek' | 'siliconflow'>('deepseek');

  // 添加模型状态管理
  const [modelStatuses, setModelStatuses] = useState<Record<string, {
    status: 'valid' | 'quota_exceeded' | 'invalid' | 'untested';
    message: string;
  }>>({
    'deepseek-chat': { status: 'untested', message: '未测试' },
    'deepseek-reasoner': { status: 'untested', message: '未测试' },
    'zhipu-glm-4': { status: 'untested', message: '未测试' },
    '01-yi-chat': { status: 'untested', message: '未测试' },
    'qwen-max': { status: 'untested', message: '未测试' },
    'moonshot-v1-128k': { status: 'untested', message: '未测试' },
    'baichuan-turbo': { status: 'untested', message: '未测试' },
  });

  // 加载设置
  const loadSettings = async () => {
    setLoading(true);
    try {
      const savedSettings = await settings.getAll();

      if (savedSettings.deepseek_api_key) {
        setDeepseekApiKey(savedSettings.deepseek_api_key);
      }

      if (savedSettings.siliconflow_api_key) {
        setSiliconflowApiKey(savedSettings.siliconflow_api_key);
      }

      // 加载提供商选择
      if (savedSettings.selected_provider) {
        setSelectedProvider(savedSettings.selected_provider);
      }

      // 加载模型选择
      if (savedSettings.selected_model) {
        setSelectedModel(savedSettings.selected_model);
        setAiModel(savedSettings.selected_model);
      } else {
        // 如果没有保存的模型选择，根据提供商设置默认模型
        const defaultProvider = savedSettings.selected_provider || 'deepseek';
        const defaultModel = defaultProvider === 'deepseek' ? 'deepseek-chat' : 'zhipu-glm-4';
        setSelectedModel(defaultModel);
        setAiModel(defaultModel);
      }

      if (savedSettings.theme) {
        setTheme(savedSettings.theme);
      }

      if (savedSettings.auto_save !== undefined) {
        setAutoSave(savedSettings.auto_save);
      }

      if (savedSettings.auto_save_interval) {
        setAutoSaveInterval(savedSettings.auto_save_interval);
      }

      if (savedSettings.editor_font_size) {
        setFontSize(savedSettings.editor_font_size);
      }

      if (savedSettings.editor_font_family) {
        setFontFamily(savedSettings.editor_font_family);
      }

      if (savedSettings.editor_line_height) {
        setLineHeight(savedSettings.editor_line_height);
      }
    } catch (error) {
      console.error('加载设置失败:', error);
      setSnackbar({
        open: true,
        message: '加载设置失败',
        severity: 'error',
      });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadSettings();
  }, []);

  // 确保selectedModel和aiModel同步
  useEffect(() => {
    setAiModel(selectedModel);
  }, [selectedModel]);

  const handleTabChange = (event: React.SyntheticEvent, newValue: number) => {
    setTabValue(newValue);
  };

  const handleSaveSettings = async () => {
    setLoading(true);
    try {
      await Promise.all([
        settings.set('deepseek_api_key', deepseekApiKey),
        settings.set('siliconflow_api_key', siliconflowApiKey),
        settings.set('selected_model', selectedModel),
        settings.set('openai_model', selectedModel),
        settings.set('theme', theme),
        settings.set('auto_save', autoSave),
        settings.set('auto_save_interval', autoSaveInterval),
        settings.set('editor_font_size', fontSize),
        settings.set('editor_font_family', fontFamily),
        settings.set('editor_line_height', lineHeight),
      ]);

      setSnackbar({
        open: true,
        message: '设置已保存',
        severity: 'success',
      });
    } catch (error) {
      console.error('保存设置失败:', error);
      setSnackbar({
        open: true,
        message: '保存设置失败',
        severity: 'error',
      });
    } finally {
      setLoading(false);
    }
  };

  const handleResetSettings = async () => {
    if (window.confirm('确定要重置所有设置吗？这将恢复默认值。')) {
      setLoading(true);
      try {
        await settings.clear();

        // 恢复默认值
        setDeepseekApiKey('');
        setSiliconflowApiKey('');
        setAiModel('deepseek-chat');
        setTheme('system');
        setAutoSave(true);
        setAutoSaveInterval(60);
        setFontSize(16);
        setFontFamily('Arial');
        setLineHeight(1.5);

        setSnackbar({
          open: true,
          message: '设置已重置为默认值',
          severity: 'info',
        });
      } catch (error) {
        console.error('重置设置失败:', error);
        setSnackbar({
          open: true,
          message: '重置设置失败',
          severity: 'error',
        });
      } finally {
        setLoading(false);
      }
    }
  };

  const handleCloseSnackbar = () => {
    setSnackbar({ ...snackbar, open: false });
  };

  const toggleApiKeyVisibility = () => {
    setShowApiKey(!showApiKey);
  };

  // 测试API键有效性的函数
  const testApiKey = async (provider: string) => {
    let apiKey = '';
    let providerName = '';
    let testModel = '';
    let apiEndpoint = '';
    let headers: Record<string, string> = {};
    let requestBody: any = {};

    switch (provider) {
      case 'deepseek':
        apiKey = deepseekApiKey;
        providerName = 'DeepSeek';
        testModel = 'deepseek-chat';
        apiEndpoint = 'https://api.deepseek.com/v1/chat/completions';
        headers = {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${apiKey}`
        };
        requestBody = {
          model: testModel,
          messages: [
            { role: 'system', content: 'You are a helpful assistant.' },
            { role: 'user', content: 'Hello, this is a test message. Please respond with a single word: "Working"' }
          ],
          temperature: 0.1,
          max_tokens: 10
        };
        break;
      case 'siliconflow':
        apiKey = siliconflowApiKey;
        providerName = 'SiliconFlow';
        testModel = 'zhipu-glm-4';
        apiEndpoint = 'https://api.siliconflow.com/v1/chat/completions';
        headers = {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${apiKey}`
        };
        requestBody = {
          model: testModel,
          messages: [
            { role: 'system', content: 'You are a helpful assistant.' },
            { role: 'user', content: 'Hello, this is a test message. Please respond with a single word: "Working"' }
          ],
          temperature: 0.1,
          max_tokens: 10
        };
        break;
      default:
        setSnackbar({
          open: true,
          message: '未知提供商',
          severity: 'error'
        });
        return;
    }

    if (!apiKey) {
      setSnackbar({
        open: true,
        message: `${providerName} API密钥为空`,
        severity: 'error',
      });
      return;
    }

    setLoading(true);
    setSnackbar({
      open: true,
      message: `正在测试 ${providerName} API密钥...`,
      severity: 'info',
    });

    try {
      // 测试API接口的简单请求
      let response;
      let success = false;
      let errorMessage = '';

      try {
        // 使用fetch发送请求
        const fetchResponse = await fetch(apiEndpoint, {
          method: 'POST',
          headers: headers,
          body: JSON.stringify(requestBody)
        });

        const responseText = await fetchResponse.text();

        // 尝试解析为JSON
        try {
          response = JSON.parse(responseText);
          if (process.env.NODE_ENV === 'development') {
            console.log('测试响应:', response);
          }
        } catch (e) {
          console.error('解析响应失败:', e);
          response = { success: false, error: responseText };
        }

        // 检查响应
        if (fetchResponse.ok) {
          success = true;

          // 更新模型状态
          setModelStatuses(prev => ({
            ...prev,
            [testModel]: {
              status: 'valid',
              message: '有效'
            }
          }));
        } else {
          // 检查是否是配额错误
          const errorText = responseText || '';
          const isQuotaError = /quota|exceed|billing|insufficient|balance/i.test(errorText);

          if (isQuotaError) {
            // 标记为配额超限
            setModelStatuses(prev => ({
              ...prev,
              [testModel]: {
                status: 'quota_exceeded',
                message: '配额超限'
              }
            }));

            errorMessage = `API密钥有效，但${providerName}配额已超限。请检查账户余额或升级计划。`;

            // 配额错误也算成功验证了密钥
            success = true;
          } else {
            // 其他错误
            setModelStatuses(prev => ({
              ...prev,
              [testModel]: {
                status: 'invalid',
                message: '无效'
              }
            }));

            errorMessage = responseText || '验证失败，未知错误';
          }
        }
      } catch (error) {
        console.error(`测试${providerName} API失败:`, error);
        errorMessage = `验证失败: ${error instanceof Error ? error.message : String(error)}`;

        // 更新模型状态
        setModelStatuses(prev => ({
          ...prev,
          [testModel]: {
            status: 'invalid',
            message: '无效'
          }
        }));
      }

      // 显示结果
      if (success) {
        setSnackbar({
          open: true,
          message: errorMessage || `${providerName} API密钥验证成功`,
          severity: errorMessage ? 'warning' : 'success',
        });
      } else {
        setSnackbar({
          open: true,
          message: errorMessage || `${providerName} API密钥验证失败`,
          severity: 'error',
        });
      }
    } catch (error) {
      console.error(`测试${providerName} API失败:`, error);
      setSnackbar({
        open: true,
        message: `测试失败: ${error instanceof Error ? error.message : String(error)}`,
        severity: 'error',
      });
    } finally {
      setLoading(false);
    }
  };

  // 渲染模型状态标记
  const renderModelStatusBadge = (modelId: string) => {
    const status = modelStatuses[modelId] || { status: 'untested', message: '未测试' };

    switch (status.status) {
      case 'valid':
        return (
          <CheckCircleIcon
            color="success"
            fontSize="small"
            sx={{ cursor: 'help' }}
            titleAccess="API验证通过"
          />
        );
      case 'quota_exceeded':
        return (
          <WarningIcon
            color="warning"
            fontSize="small"
            sx={{ cursor: 'help' }}
            titleAccess="API密钥有效，但配额已超限或账户余额不足"
          />
        );
      case 'invalid':
        return (
          <ErrorIcon
            color="error"
            fontSize="small"
            sx={{ cursor: 'help' }}
            titleAccess="API密钥无效"
          />
        );
      case 'untested':
      default:
        return (
          <InfoIcon
            color="disabled"
            fontSize="small"
            sx={{ cursor: 'help' }}
            titleAccess="未测试"
          />
        );
    }
  };

  // 获取当前模型对应的API提供商名称
  const getCurrentProviderName = () => {
    const provider = getModelProvider(selectedModel || '');
    switch (provider) {
      case 'deepseek': return 'DeepSeek';
      case 'siliconflow': return 'SiliconFlow';
      default: return '未知提供商';
    }
  };

  // 处理模型选择变更 - 简化为直接函数
  const handleModelChange = (value: string) => {
    setSelectedModel(value);
    saveModelSelection(value);
  };

  // 保存模型选择到设置
  const saveModelSelection = (modelId: string) => {
    // 避免使用setTimeout，直接执行异步操作
    (async () => {
      try {
        await Promise.all([
          settings.set('selected_model', modelId),
          settings.set('openai_model', modelId)
        ]);

        setSnackbar({
          open: true,
          message: `已选择模型: ${getModelName(modelId)}`,
          severity: 'success',
        });
      } catch (error) {
        console.error('保存模型选择失败:', error);
        setSnackbar({
          open: true,
          message: '保存模型选择失败',
          severity: 'error',
        });
      }
    })();
  };

  // 处理提供商选择变更 - 简化为直接函数
  const handleProviderChange = (newProvider: 'deepseek' | 'siliconflow') => {
    setSelectedProvider(newProvider);

    // 根据新提供商自动选择默认模型
    const defaultModel = newProvider === 'deepseek' ? 'deepseek-chat' : 'zhipu-glm-4';

    // 更新模型选择
    setSelectedModel(defaultModel);

    // 保存到设置中
    (async () => {
      try {
        await Promise.all([
          settings.set('selected_provider', newProvider),
          settings.set('selected_model', defaultModel),
          settings.set('openai_model', defaultModel)
        ]);

        setSnackbar({
          open: true,
          message: `已切换到${newProvider === 'deepseek' ? 'DeepSeek' : '硅基流动'}服务`,
          severity: 'success',
        });
      } catch (error) {
        console.error('保存提供商选择失败:', error);
        setSnackbar({
          open: true,
          message: '保存提供商选择失败',
          severity: 'error',
        });
      }
    })();
  };

  // 更新getModelProvider函数
  const getModelProvider = (model: string): 'deepseek' | 'siliconflow' | 'unknown' => {
    const modelLower = model.toLowerCase();
    if (modelLower.includes('deepseek')) {
      return 'deepseek';
    } else if (
      modelLower.includes('glm') ||
      modelLower.includes('zhipu') ||
      modelLower.includes('yi') ||
      modelLower.includes('qwen') ||
      modelLower.includes('moonshot') ||
      modelLower.includes('baichuan')
    ) {
      return 'siliconflow';
    } else {
      return 'unknown';
    }
  };

  return (
    <Box sx={{ width: '100%', p: 2 }}>
      <Typography variant="h5" gutterBottom>
        设置
      </Typography>

      <Box sx={{ borderBottom: 1, borderColor: 'divider', mb: 2 }}>
        <Tabs value={tabValue} onChange={handleTabChange} aria-label="设置选项卡">
          <Tab label="AI 设置" id="settings-tab-0" />
          <Tab label="编辑器" id="settings-tab-1" />
          <Tab label="外观" id="settings-tab-2" />
          <Tab label="通用" id="settings-tab-3" />
        </Tabs>
      </Box>

      <Paper sx={{ p: 2, mb: 2 }}>
        <TabPanel value={tabValue} index={0}>
          <Typography variant="h6" gutterBottom>
            AI 服务配置
          </Typography>

          {/* 添加提供商选择 */}
          <FormControl fullWidth sx={{ mb: 2 }}>
            <Typography variant="subtitle2" gutterBottom>
              选择AI服务提供商
            </Typography>
            <Select
              native
              value={selectedProvider}
              onChange={(e) => {
                handleProviderChange(e.target.value as 'deepseek' | 'siliconflow');
              }}
              inputProps={{
                name: 'provider',
                id: 'provider-select',
              }}
            >
              <option value="deepseek">DeepSeek</option>
              <option value="siliconflow">硅基流动</option>
            </Select>
          </FormControl>

          <FormControl fullWidth sx={{ mb: 2 }}>
            <Typography variant="subtitle2" gutterBottom>
              选择AI模型
            </Typography>
            <Select
              native
              value={selectedModel}
              onChange={(e) => handleModelChange(e.target.value)}
              inputProps={{
                name: 'model',
                id: 'model-select',
              }}
            >
              {selectedProvider === 'deepseek' ? (
                <>
                  <option value="deepseek-chat">DeepSeek Chat (V3)</option>
                  <option value="deepseek-reasoner">DeepSeek Reasoner (R1)</option>
                </>
              ) : (
                <>
                  <option value="zhipu-glm-4">智谱 GLM-4</option>
                  <option value="01-yi-chat">零一万物 YI Chat</option>
                  <option value="qwen-max">通义千问 Qwen2</option>
                  <option value="moonshot-v1-128k">Moonshot V1-128K</option>
                  <option value="baichuan-turbo">百川 Turbo</option>
                </>
              )}
            </Select>
          </FormControl>

          {/* 当前选择的模型信息 */}
          <Paper elevation={1} sx={{ p: 2, mb: 2, bgcolor: 'background.default' }}>
            <Typography variant="subtitle2">当前选择: {getModelName(selectedModel)}</Typography>
            <Typography variant="body2" color="text.secondary">
              提供商: {getCurrentProviderName()}
            </Typography>
            <Typography variant="body2" color="text.secondary">
              状态: {
                modelStatuses[selectedModel]?.status === 'valid' ? '可用' :
                  modelStatuses[selectedModel]?.status === 'quota_exceeded' ? '配额超限' :
                    modelStatuses[selectedModel]?.status === 'invalid' ? '无效' : '未测试'
              }
            </Typography>

            {/* 如果当前模型配额超限，显示警告和建议 */}
            {modelStatuses[selectedModel]?.status === 'quota_exceeded' && (
              <Alert severity="warning" sx={{ mt: 1 }}>
                <AlertTitle>配额超限警告</AlertTitle>
                当前选择的模型配额已超限或账户余额不足。您可以:
                <ul>
                  <li>检查账户余额并充值</li>
                  <li>更换为其他可用模型</li>
                  <li>等待配额刷新（如果使用免费额度）</li>
                </ul>
              </Alert>
            )}
          </Paper>

          {/* API密钥配置 */}
          <Typography variant="subtitle1" gutterBottom>
            DeepSeek API密钥
          </Typography>
          <Box sx={{ display: 'flex', mb: 2 }}>
            <TextField
              fullWidth
              type={showApiKey ? 'text' : 'password'}
              value={deepseekApiKey}
              onChange={(e) => setDeepseekApiKey(e.target.value)}
              placeholder="..."
              size="small"
              sx={{ mr: 1 }}
            />
            <IconButton onClick={toggleApiKeyVisibility} size="small">
              {showApiKey ? <VisibilityOffIcon /> : <VisibilityIcon />}
            </IconButton>
            <Button onClick={() => testApiKey('deepseek')} disabled={loading || !deepseekApiKey}>
              测试
            </Button>
          </Box>

          <Typography variant="subtitle1" gutterBottom>
            硅基流动 API密钥
          </Typography>
          <Box sx={{ display: 'flex', mb: 2 }}>
            <TextField
              fullWidth
              type={showApiKey ? 'text' : 'password'}
              value={siliconflowApiKey}
              onChange={(e) => setSiliconflowApiKey(e.target.value)}
              placeholder="..."
              size="small"
              sx={{ mr: 1 }}
            />
            <IconButton onClick={toggleApiKeyVisibility} size="small">
              {showApiKey ? <VisibilityOffIcon /> : <VisibilityIcon />}
            </IconButton>
            <Button onClick={() => testApiKey('siliconflow')} disabled={loading || !siliconflowApiKey}>
              测试
            </Button>
          </Box>
        </TabPanel>

        <TabPanel value={tabValue} index={1}>
          <Typography variant="h6" gutterBottom>
            编辑器设置
          </Typography>

          <FormControl fullWidth sx={{ mb: 2 }}>
            <Select
              labelId="font-family-label"
              id="font-family-select"
              value={fontFamily}
              label="字体"
              onChange={(e) => setFontFamily(e.target.value)}
            >
              <MenuItem value="Arial">Arial</MenuItem>
              <MenuItem value="Times New Roman">Times New Roman</MenuItem>
              <MenuItem value="Courier New">Courier New</MenuItem>
              <MenuItem value="Georgia">Georgia</MenuItem>
              <MenuItem value="Verdana">Verdana</MenuItem>
            </Select>
          </FormControl>

          <FormControl fullWidth sx={{ mb: 2 }}>
            <Select
              labelId="font-size-label"
              id="font-size-select"
              value={fontSize}
              label="字体大小"
              onChange={(e) => setFontSize(Number(e.target.value))}
            >
              {[12, 14, 16, 18, 20, 22, 24].map((size) => (
                <MenuItem key={size} value={size}>
                  {size}px
                </MenuItem>
              ))}
            </Select>
          </FormControl>

          <FormControl fullWidth sx={{ mb: 2 }}>
            <Select
              labelId="line-height-label"
              id="line-height-select"
              value={lineHeight}
              label="行高"
              onChange={(e) => setLineHeight(Number(e.target.value))}
            >
              {[1, 1.2, 1.5, 1.8, 2, 2.2, 2.5].map((height) => (
                <MenuItem key={height} value={height}>
                  {height}
                </MenuItem>
              ))}
            </Select>
          </FormControl>

          <FormControlLabel
            control={
              <Switch
                checked={autoSave}
                onChange={(e) => setAutoSave(e.target.checked)}
              />
            }
            label="启用自动保存"
          />

          {autoSave && (
            <FormControl fullWidth sx={{ mt: 2 }}>
              <Select
                labelId="auto-save-interval-label"
                id="auto-save-interval-select"
                value={autoSaveInterval}
                label="自动保存间隔 (秒)"
                onChange={(e) => setAutoSaveInterval(Number(e.target.value))}
              >
                <MenuItem value={30}>30 秒</MenuItem>
                <MenuItem value={60}>1 分钟</MenuItem>
                <MenuItem value={120}>2 分钟</MenuItem>
                <MenuItem value={300}>5 分钟</MenuItem>
              </Select>
            </FormControl>
          )}
        </TabPanel>

        <TabPanel value={tabValue} index={2}>
          <Typography variant="h6" gutterBottom>
            外观设置
          </Typography>

          <FormControl fullWidth sx={{ mb: 2 }}>
            <Select
              labelId="theme-label"
              id="theme-select"
              value={theme}
              label="主题"
              onChange={(e) => setTheme(e.target.value as 'light' | 'dark' | 'system')}
            >
              <MenuItem value="light">浅色</MenuItem>
              <MenuItem value="dark">深色</MenuItem>
              <MenuItem value="system">跟随系统</MenuItem>
            </Select>
          </FormControl>
        </TabPanel>

        <TabPanel value={tabValue} index={3}>
          <Typography variant="h6" gutterBottom>
            通用设置
          </Typography>

          <Alert severity="warning" sx={{ mb: 3 }}>
            <AlertTitle>重置设置</AlertTitle>
            重置将恢复所有设置为默认值，包括API密钥。
          </Alert>

          <Button
            variant="outlined"
            color="secondary"
            startIcon={<RefreshIcon />}
            onClick={handleResetSettings}
            sx={{ mr: 2 }}
          >
            重置所有设置
          </Button>
        </TabPanel>
      </Paper>

      <Box sx={{ display: 'flex', justifyContent: 'flex-end', mt: 2 }}>
        <Button
          variant="contained"
          color="primary"
          startIcon={<SaveIcon />}
          onClick={handleSaveSettings}
          disabled={loading}
        >
          保存设置
        </Button>
      </Box>

      <Snackbar
        open={snackbar.open}
        autoHideDuration={6000}
        onClose={handleCloseSnackbar}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
      >
        <Alert onClose={handleCloseSnackbar} severity={snackbar.severity}>
          {snackbar.message}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default SettingsPanel; 